package cn.edu.zut.salarymanagesystem.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.haibin.calendarview.Calendar;

import java.io.IOException;
import java.text.SimpleDateFormat;

import cn.edu.zut.salarymanagesystem.R;
import cn.edu.zut.salarymanagesystem.bean.pojo.Attendence;
import cn.edu.zut.salarymanagesystem.bean.vo.OperateResult;
import cn.edu.zut.salarymanagesystem.config.Storage;
import cn.edu.zut.salarymanagesystem.fragments.PersonFragment;
import cn.edu.zut.salarymanagesystem.fragments.QueryFragment;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class AlertBuilder {
    public static Request toSendRequest = null;
    private static QueryFragment queryFragment = null;
    private static PersonFragment personFragment = null;
    private static int pos = -1;
    private static final byte NETWORK_ERROR = 0x01;
    private static final byte CANCEL_SUCCESS = 0x02;
    private static final byte CANCEL_ERROR = 0x03;
    private static Handler handler = null;
    private static SimpleDateFormat format = new SimpleDateFormat("yy年MM月dd日");

    public static AlertDialog getAddDialog(Context context, String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("提示:");
        builder.setMessage(msg);
        builder.setPositiveButton("好的", null);
        return builder.create();
    }

    public static AlertDialog getDeleteDialog(QueryFragment queryFragment, String msg, int ifSuccessDeletePos) {
        pos = ifSuccessDeletePos;
        AlertDialog.Builder builder = new AlertDialog.Builder(queryFragment.getActivity());
        AlertBuilder.queryFragment = queryFragment;
        builder.setTitle("提示:");
        builder.setMessage(msg);
        builder.setPositiveButton("确定", listener);
        builder.setNegativeButton("取消", null);
        return builder.create();
    }

    public static AlertDialog getDialog(QueryFragment queryFragment, String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(queryFragment.getActivity());
        AlertBuilder.queryFragment = queryFragment;
        builder.setTitle("当前选择的记录如下所示:");
        builder.setMessage(msg);
        builder.setPositiveButton("确定", null);
        return builder.create();
    }

    public static AlertDialog getCancelDialog(PersonFragment personFragment, Handler handler) {
        AlertBuilder.handler = handler;
        AlertDialog.Builder builder = new AlertDialog.Builder(personFragment.getActivity());
        builder.setTitle("是否要取消签到?");
        builder.setPositiveButton("确定", listenerCancel);
        return builder.create();
    }

    private static DialogInterface.OnClickListener listenerCancel = (dialog, i) -> {
        OkHttpClient client = Browser.getClient();
        Request request = new Request.Builder().url(Storage.url + "/attendance/cancel?uid=" + Storage.currentUser.getUid()).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Toast.makeText(personFragment.getActivity(), "请求失败！请检查网络设置", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String result = response.body().string();
                //TODO:这里等赛后修复
                OperateResult operateResult = JSON.parseObject(result, OperateResult.class);
                Log.i("d8g", "handleMessage: " + operateResult.toString());
                try {
                    Message obtain = Message.obtain();
                    obtain.what = 0x07;
                    obtain.obj = operateResult;
                    handler.sendMessage(obtain);
                } catch (Exception e) {
                    Log.e("d8g", e.getMessage());
                }
            }
        });
    };
    private static DialogInterface.OnClickListener listener = (dialogInterface, i) -> {
        if (toSendRequest == null) {
            Toast.makeText(queryFragment.getActivity(), "应用程序出错了！", Toast.LENGTH_SHORT).show();
            return;
        }
        Browser.getClient().newCall(toSendRequest).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Toast.makeText(queryFragment.getActivity(), "应用程序出错了！" + e.getMessage(), Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String string = response.body().string();
                Message message = new Message();
                message.what = QueryFragment.FLUSH_LIST;
                Log.i("d8g", string);
                if (string.equals("1")) {
                    message.arg1 = pos;
                    message.arg2 = 1;
                } else {
                    message.arg2 = 0;
                }
                queryFragment.handler.sendMessage(message);
            }
        });
    };

    public static AlertDialog getAttendanceDialog(Activity context, Handler handler) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        final LayoutInflater inflater = context.getLayoutInflater();
        View convertView = inflater.inflate(R.layout.attendance_windows, null);
        builder.setView(convertView);
        AlertDialog alertDialog = builder.create();

        // 提取控件
        Button confirm = convertView.findViewById(R.id.btn_confirm);
        Button cancel = convertView.findViewById(R.id.btn_cancel);
        RadioGroup radioGroup = convertView.findViewById(R.id.radioGroup);
        EditText editComment = convertView.findViewById(R.id.edit_comment);
        EditText editOvertimeHours = convertView.findViewById(R.id.edit_overtime_hours);
        // 设置单选框组监听事件
        radioGroup.clearCheck();
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.radio_overtime) {
                editOvertimeHours.setEnabled(true);
                editOvertimeHours.setVisibility(View.VISIBLE);
            } else {
                editOvertimeHours.setVisibility(View.GONE);
                editOvertimeHours.setEnabled(false);
            }
        });

        // 确定按钮点击事件
        confirm.setOnClickListener(view -> {
            int selectedId = radioGroup.getCheckedRadioButtonId();
            RadioButton selectedRadioButton = convertView.findViewById(selectedId);
            String comment = editComment.getText().toString();
            StringBuilder params = new StringBuilder();
            switch (selectedId) {
                case R.id.radio_full_day:
                    // 处理全天的逻辑
                    params.append("?flag=0");
                    break;
                case R.id.radio_half_day:
                    // 处理半天假逻辑
                    params.append("?flag=1");
                    break;
                case R.id.radio_overtime:
                    //  处理加班逻辑
                    String hour = editOvertimeHours.getText().toString().equals("") ? "0" : editOvertimeHours.getText().toString();
                    Toast.makeText(context, "" + hour, Toast.LENGTH_SHORT).show();
                    params.append("?flag=2&hour=").append(hour);
            }
            if (!comment.equals("")) {
                params.append("&message=").append(comment);
            }
            Request request = new Request.Builder().url(Storage.url + "/attendance/comin" + params).build();
            OkHttpClient client = Browser.getClient();
            String TAG = "d8g";
            client.newCall(request).enqueue(
                    new Callback() {
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                            Log.e(TAG, "Comin onFailure: " + e.getMessage());
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                            String result = response.body().string();
                            if (result.equals("SUCCESS")) {
                                handler.sendEmptyMessage(0x04);
                            } else if (result.equals("ALREADY")) {
                                handler.sendEmptyMessage(0x05);
                            } else {
                                handler.sendEmptyMessage(0x06);
                                Log.e(TAG, "onResponse:签到结果返回异常 " + result);
                            }
                        }
                    }
            );
            // 关闭弹窗
            alertDialog.dismiss();
        });

        // 取消按钮点击事件
        cancel.setOnClickListener(view -> alertDialog.dismiss());
        return alertDialog;
    }

    public static AlertDialog getDayDialog(Activity context, Attendence attendence, Calendar calendar) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        final LayoutInflater inflater = context.getLayoutInflater();
        View convertView = inflater.inflate(R.layout.attendance_detail, null);
        builder.setView(convertView);
        AlertDialog alertDialog = builder.create();
        convertView.findViewById(R.id.btn_confirm).setOnClickListener(v -> alertDialog.dismiss());

        TextView status = convertView.findViewById(R.id.tv_attendance_status);
        TextView remark = convertView.findViewById(R.id.tv_message);
        TextView hours = convertView.findViewById(R.id.tv_hours);
        TextView date = convertView.findViewById(R.id.tv_data);
        date.setText(calendar.getYear() + "年" + (calendar.getMonth()) + "月" + calendar.getDay() + "日");
        status.setText(attendence.getFlag() == 0 ? "全天班" : attendence.getFlag() == 1 ? "半天班" : "小时班");
        remark.setText(attendence.getCommentary() == null || attendence.getCommentary().equals("") ? "无" : attendence.getCommentary());
        float hour = attendence.getFlag() == 0 ? 8.0f : attendence.getFlag() == 1 ? 4.0f : attendence.getHour();
        hours.setText(hour + "时");
        return alertDialog;
    }

}
